package web;

import domain.ClubAdministrator;
import domain.SystemAdministrator;
import domain.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 请求过滤器
 * 对请求进行登录校验
 *
 * @author zdc
 */
@WebFilter("/campus")
public class RequestFilter implements Filter {

    /**
     * Filter初始化
     *
     * @param filterConfig Filter配置
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("LoginFilter initialized");
    }

    /**
     * 处理请求
     *
     * @param request 请求对象
     * @param response 响应对象
     * @param chain Filter链
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        HttpSession session = httpRequest.getSession(false); // 获取当前session，如果当前没有session则返回null

        if (session == null || session.getAttribute("user") == null) {
            // 如果用户未登录，重定向到登录页面
            httpResponse.sendRedirect(httpRequest.getContextPath() + "/login");
        } else {
            // 如果用户已登录，根据用户类型进行不同的处理
            Object user = session.getAttribute("user");
            if (user instanceof ClubAdministrator) {
                System.out.println("User is a ClubAdministrator");
            } else if (user instanceof SystemAdministrator) {
                System.out.println("User is a SystemAdministrator");
            }

            chain.doFilter(request, response);
        }
    }

    /**
     * 销毁 Filter
     */
    @Override
    public void destroy() {
        System.out.println("LoginFilter destroyed");
    }
}

